#!/bin/bash  

DIR=${HOME} 
LOG_DIR=${HOME}/log
# 目标文件路径  
TARGET_FILE="$LOG_DIR/top_processes.log"  
# 文件大小限制（以字节为单位）10M
MAX_FILE_SIZE=10485760  
MAX_FILE_NUM=3
MAX_PROC_MONITOR=5

function get_current_time {  
    date "+%Y-%m-%d %H:%M:%S"  
}  

TARGET_BASE="${TARGET_FILE%.*}"

while true; do  
    if [ -f "$TARGET_FILE" ]; then
	    # 检查文件大小  
	    FILE_SIZE=$(stat -c%s "$TARGET_FILE")  
	  
	    # 如果文件大小超过限制  
	    if [ "$FILE_SIZE" -gt "$MAX_FILE_SIZE" ]; then  
		
		counter=$((MAX_FILE_NUM-2))  
		while [ $counter -ge 1 ]; do  
			file_to_check="${TARGET_BASE}.$counter.log"  
			if [ -f "$file_to_check" ]; then  
				mv "$file_to_check" "${TARGET_BASE}.$((counter+1)).log"  
			fi  
			((counter--)) 
		done  

		# 重命名当前文件  
		mv "$TARGET_FILE" "${TARGET_BASE}.1.log"  
	    	# echo "当前文件 $TARGET_FILE 已重命名为 $TARGET_FILE.1"  
	    fi  
    fi
    
    TIMESTAMP=$(get_current_time)  
    PROCESSES=$(ps aux --sort=-%cpu | head -n 6 | tail -n $MAX_PROC_MONITOR) 
    CPU_USAGE=$(top -bn1 | awk -F, '/Cpu$s$:/ {gsub(/[^0-9.]/, "", $4); print 100-$4"%"}')

    echo "$TIMESTAMP-----------------------" >> "$TARGET_FILE"    
    echo "Total CPU Usage: $CPU_USAGE" >> "$TARGET_FILE"
    echo "USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND" >> "$TARGET_FILE"
    echo -e "$PROCESSES\n" >> "$TARGET_FILE"  
    
    # 等待 1 秒  
    sleep 1  
done
